<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/22
 * Time: 12:27
 */

namespace app\store\controller;

use app\core\InitController;

use redis\Redis;
use think\facade\View;
use app\store\model\Article;
use app\store\model\Notice;
use app\store\model\ClickLog;
use app\store\model\Keyword as Words;
use app\store\model\User;
use app\store\validate\Chat as ChatValidate;
use app\store\controller\Index;
class Detail extends InitController
{
    /**
     * 详情
     * @return string|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/12 21:24
     */
    public function index()
    {
        $get = $this->request->get('Art');
    
         if(is_numeric($get)){// 判断是否数字
           $id = $get;
         }else{
           $id = base64_decode($get); // 解密
         }
        if (!$id) { // 恶意请求跳转到主页
            return redirect('/');
        }
        $user_id = $this->user['id']??0;//定义默认ID
        $user_ip = $this->request->ip();//定义默认ip
        Article::view($id, $user_id, $user_ip);// 浏览view+1
        $article = Article::findArticle($id);//查询
        $modle = Notice::notice($id);//回复评论  
            // 渲染视图
      View::assign([
            'reply'      => $modle['reply'],//一级回复
            'count'      => $modle['count'],//回复共多少条
            'min'        => Article::minCode($article['cat_id']),//上一页
            'max'        => Article::maxCode($article['cat_id']),//下一页
            'last'       => Article::lastCode($article['id'], $article['cat_id']),//上一篇 
            'next'       => Article::nextCode($article['id'], $article['cat_id']),//下一篇
            'clickLog'   => ClickLog::findClickLog($id, $user_id, $user_ip),//判断是否点赞
            'article'    => $article,//数据
            'reading'    => Index::cars()['reply']
        ]);
        return View::fetch('detail');
    }

    /**
     * 点赞
     * @return array
     * @author: MK
     * @Time: 2020/4/12 22:04
     */
    public function click()
    {
            $user_id = $this->user['id']??0;//定义默认ID
            $article_id = $this->request->post('article_id');
            $user_ip = $this->request->ip();//定义默认ip
              if ($user_id==0) {
          return ['code' => 0, 'msg' => '请登录后再点赞评论！'];
        }
            $res = Article::click($user_id, $article_id, $user_ip);
            return $res ? $this->success('', '', __('Like success'),'', 1) : $this->error();
    }
    ///聊天
    public function chatzone()
    {
       $param = $this->request->param();
        // 实例化验证器
        $validate = new ChatValidate();
        $ContentValidate = $validate->check($param);

        // 输出验证器错误信息
        if (true !== $ContentValidate) return $this->error($validate->getError());

        /*/过滤关键字*/
        $model = Words::keyWordCheck();
        $item = [];

         foreach($model as $k=>$v)
         {
            $item[$k] = $v['word'];
         }
        
        $param['content'] = str_replace($item,"<font color='#ff0000;'>{此处关键词违规}</font>",$param['content']);
        //$replace =array_combine($item,array_fill(0,count($item),'*'));
        //$content = strtr($param['content'],$replace);
        
        if($param['replys']=="1"){
               Notice::update(['content'=>$param['content']],['id'=>$param['pid_id']]);
               add_user_log('notices', '审核成功');// 记录行为日志
                 return ['code' => 0, 'msg' => '审核成功'];
            }

    if($param['replys']){
        $replystitle = $param['replys'] . $param['content'];
        $reply = $param['content'];
    }else{
        $replystitle = $param['content'];
        $reply = "";  
    }
        $newData = [
            'pid_id'     => $param['pid_id'],
            'uid'        => $param['uid'],
            'datetime'   => date("Y-m-d", time()),
            'user_id'    => $this->user['id'],
            'content'    => $replystitle,
            'reply'      => $reply,
            'ip'         => $this->request->ip(),
        ];
        $result = Notice::add($newData);
        return $result ? $this->success('', 0, '留言成功！', 1) : $this->error();
    }

    
    // 评论 public function notices(Redis $redis)
    public function notices(Redis $redis)
    {
            $param = $this->request->param();
            
           // 验证条件
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'chat');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
        /*/过滤关键字*/
        $model = Words::keyWordCheck();
        $item = [];

         foreach($model as $k=>$v)
         {
            $item[$k] = $v['word'];
         }
        
        //$replace =array_combine($item,array_fill(0,count($item),'*'));
        //$param['content'] = strtr($param['content'],$replace);
        $param['content'] = str_replace($item,"<font color='#ff0000;'>{此处关键词违规}</font>",$param['content']);
        if($param['replys']=="1"){
               Notice::update(['content'=>$param['content']],['id'=>$param['pid']]);
               add_user_log('notices', '审核成功');// 记录行为日志
                 return ['code' => 1, 'msg' => '审核成功'];
            }

         /*过滤关键字结束*/
    if($param['replys']){
        $replystitle = $param['replys'] . $param['content'];
        $reply = $param['content'];
    }else{
        $replystitle = $param['content'];
        $reply = "";  
    }
        $newData = [
            'pid'        => $param['pid'],
            'uid'        => $param['uid'],
            'datetime'   => date("Y-m-d", time()),
            'article_id' => $param['article_id'],
            'user_id'    => $this->user['id'],
            'content'    => $replystitle,
            'reply'      => $reply,
            'ip'         => $this->request->ip(),
        ];
        //if (true !== $redis->checkRule()) return $this->error(__('Take a break and comment'));
        //评论活动积分
            $modle = User::where(['id' => $this->user['id']])->find();
          
            if ($modle) {
                $count = Notice::where(['user_id' => $this->user['id']])->whereTime('create_time', 'today')->count();
                if($count <= 9)
                {
               $modle->save(['score' => $modle->score+2]);
               $res = Notice::add($newData);
            add_user_log('notices', '文章');
        return $res ? $this->success('', '', __('Comment success! Get 2 points'),'' , 1) : $this->error('评论失败！'); 
                }else{

        $res = Notice::add($newData);
            add_user_log('notices', '文章');
        return $res ? $this->success('', '', __('Comment success'),'' , 1) : $this->error(__('Comment failed'));   
                }
        }

    }
}
